<template>
  <div class="c-information">
    <!-- 好友列表栏 -->
    <Firend @toChatContent="toChatContent" :list="firiedList"></Firend>
    <div class="c-information__info">
      <!-- 聊天区域 -->
      <FirendInfo ref="firendInfo" :firend="firiedList[selectFirendIndex]" v-show="selectFirendIndex != -1"
        @acceptData="acceptData">
      </FirendInfo>
    </div>

  </div>
</template>

<script setup>
import Firend from '@/layout/Friend/Index.vue';
import FirendInfo from '@/layout/FirendInfo/Index.vue';
import { ref, onMounted, useTemplateRef } from 'vue';
import subscribe from '@/utils/subscribe.js'
import { useRoute, useRouter } from 'vue-router';
import { getShowBuddyApi, addShowBuddyApi } from '@/api/buddy.js'
import { getUserInfoByuserIdApi } from '@/api/user.js'

// 对象
const firiedList = ref([]);
const selectFirendIndex = ref(-1)
const firendInfo = useTemplateRef("firendInfo")
const router = useRouter();
const route = useRoute();
//监听消息
subscribe.on("WEBSOCKET:CHITCHAT", data => {
  let index = firiedList.value.findIndex(item => item.user.userId === data.fromId)
  // 如果监听到消息的对象 还没有创建出来 则请求数据
  if (index === -1) {
    // 获取到用户信息
    getUserInfoByuserIdApi(data.fromId).then(userInfo => {
      const obj = {
        user: userInfo,
        createTime: new Date().toLocaleDateString(),//肯定是一个时间搓
        msgList: [{ ...data, isMy: false }]//消息集合
      }
      firiedList.value.unshift(obj);
    })
    // todo 发送添加请求
    addShowBuddyApi(data.fromId);
  } else {
    firiedList.value[index].msgList.push({ ...data, isMy: false })
  }



  firendInfo.value.scrollBottom();

})

//  评论 回显
function acceptData (data) {

  firiedList.value[selectFirendIndex.value].msgList.push({ ...data, isMy: true })
}

onMounted(async () => {
  const userList = await getShowBuddyApi();
  console.log(userList);
  for (let i = 0; i < userList.length; i++) {
    firiedList.value.push({
      user: userList[i],
      createTime: new Date().toLocaleDateString(),//肯定是一个时间搓
      msgList: []//消息集合
    })
  }
  toChatContent({ user: { userId: route.params.id } })
})

function toChatContent (firend) {
  if (firend.user.userId != route.params.id) {
    router.replace("/" + firend.user.userId)
  }
  // 获取索引
  let index = firiedList.value.findIndex(item => item.user.userId == firend.user.userId)
  if (index === -1) return;
  // 跳转
  selectFirendIndex.value = index;
}

</script>

<style lang="scss" scoped>
.c-information {
  display: flex;
  flex: 1 1 0;
  background-color: white;

  &__info {
    box-shadow: -1px 0px 1px 0px $shadow-border;
    width: 100%;

  }
}
</style>